// MiniHttpServer.h

#pragma once

#include <memory>

#include "IHttpListener.h"

namespace Poco
{
	namespace Net
	{
		class HTTPServer;
		class HTTPServerRequest;
		class HTTPServerResponse;
	};
};

namespace MiniHttpServer {
	class HttpContextHandler;

	ref class HttpListener : public IHttpListener, public System::IDisposable
	{

	protected:
		HttpListener(System::Net::IPAddress^ ipAddress, int nPort);
		virtual ~HttpListener();
		!HttpListener();

	public:
		static HttpListener^ Create(System::Net::IPAddress^ ipAddress, int nPort);

		virtual void Start() override;
		virtual void Stop() override;
		virtual property bool IsStarted { bool get() override{ return m_httpServer != nullptr; }; };

		virtual void SetRequestReceiver(RequestReceiverDelegate^ handler) override;

	private:
		delegate void RequestHandlerDelegate(Poco::Net::HTTPServerRequest&, Poco::Net::HTTPServerResponse&, std::shared_ptr<HttpContextHandler> const&);
		static void DelegateCaller(gcroot<RequestHandlerDelegate^> const& caller, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response, std::shared_ptr<HttpContextHandler> const& pContext);
		void RequestHandler(Poco::Net::HTTPServerRequest&, Poco::Net::HTTPServerResponse&, std::shared_ptr<HttpContextHandler> const&);

		RequestReceiverDelegate^ m_requestReceiver;
		System::Net::IPAddress^ m_ipAddress;
		int m_nPort;
		Poco::Net::HTTPServer* m_httpServer;
	};
}
